<template>
  <div class="users-management">
    <!-- 页面头部 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">《永恒的高迪·圣家堂》管理系统</h1>
          <p class="page-subtitle">VR大空间展览体验 - 匿名用户管理</p>
        </div>
        <div class="header-right">
          <button class="back-btn" @click="goBack">
            <span class="btn-content">
              <span class="btn-icon">←</span>
              返回仪表板
            </span>
          </button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">👥</div>
          <div class="stat-content">
            <div class="stat-number">{{ stats.totalUsers }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户数据查询区域 -->
    <div class="users-section">
      <div class="section-header">
        <h2 class="section-title">匿名用户数据查询</h2>
        <div class="section-actions">
          <button class="export-btn" @click="exportUsers" :disabled="exportLoading">
            <span v-if="!exportLoading" class="btn-content">
              <span class="btn-icon">📄</span>
              导出数据
            </span>
            <span v-else class="btn-loading">
              <span class="loading-spinner"></span>
              导出中...
            </span>
          </button>
        </div>
      </div>

      <!-- 查询条件 -->
      <div class="search-panel">
        <div class="search-form">
          <div class="form-row">
            <div class="form-item">
              <label>访问日期范围：</label>
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                :shortcuts="dateShortcuts"
                @change="handleFilterChange"
              />
            </div>
            
            <div class="form-item">
              <label>排序方式：</label>
              <el-select 
                v-model="searchForm.sortType" 
                placeholder="请选择排序方式"
                @change="handleFilterChange"
              >
                <el-option label="访问时间(倒序)" value="desc"></el-option>
                <el-option label="访问时间(正序)" value="asc"></el-option>
              </el-select>
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-item">
              <label>综合搜索：</label>
              <el-input
                v-model="searchForm.searchText"
                placeholder="支持搜索用户标识、IP地址、设备指纹"
                clearable
                @keyup.enter="searchUsers"
              />
            </div>
          </div>
          
          <div class="form-actions">
            <button class="search-btn" @click="searchUsers">
              <span class="btn-content">
                <span class="btn-icon">🔍</span>
                查询用户
              </span>
            </button>
            <button class="reset-btn" @click="resetSearch">
              <span class="btn-content">
                <span class="btn-icon">🔄</span>
                重置条件
              </span>
            </button>
          </div>
        </div>
      </div>

      <!-- 用户数据表格 -->
      <div class="table-panel">
        <div class="table-header">
          <div class="table-info">
            <span class="table-count">共找到 {{ total }} 个匿名用户</span>
          </div>
        </div>
        
        <div class="table-container">
          <el-table 
            :data="users" 
            style="width: 100%"
            :loading="tableLoading"
            empty-text="暂无用户数据"
            stripe
            border
            height="500"
          >
            <el-table-column prop="userToken" label="用户标识" width="200" fixed="left">
              <template #default="scope">
                <span class="user-token">{{ scope.row.userToken }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="deviceFingerprint" label="设备指纹" width="150">
              <template #default="scope">
                <span class="device-fingerprint">{{ truncate(scope.row.deviceFingerprint, 20) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="ipAddress" label="IP地址" width="130">
              <template #default="scope">
                <span class="ip-address">{{ scope.row.ipAddress }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="userAgent" label="浏览器信息" width="200">
              <template #default="scope">
                <span class="user-agent" :title="scope.row.userAgent">
                  {{ truncate(scope.row.userAgent, 30) }}
                </span>
              </template>
            </el-table-column>
            
            <el-table-column prop="firstVisitTime" label="首次访问" width="150">
              <template #default="scope">
                <span class="visit-time">{{ formatDateTime(scope.row.firstVisitTime) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="lastVisitTime" label="最后访问" width="150">
              <template #default="scope">
                <span class="visit-time">{{ formatDateTime(scope.row.lastVisitTime) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="visitCount" label="访问次数" width="100">
              <template #default="scope">
                <el-tag type="info" size="small">
                  {{ scope.row.visitCount || 0 }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="bookingCount" label="预约次数" width="100">
              <template #default="scope">
                <el-tag 
                  :type="scope.row.bookingCount > 0 ? 'success' : 'info'" 
                  size="small"
                >
                  {{ scope.row.bookingCount || 0 }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="createdAt" label="创建时间" width="150">
              <template #default="scope">
                <span class="created-time">{{ formatDateTime(scope.row.createdAt) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="scope">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="viewUserDetail(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 用户详情弹窗 -->
    <el-dialog
      v-model="userDetailDialogVisible"
      title="用户详情"
      width="600px"
      :show-close="true"
    >
      <div class="user-detail-dialog" v-if="selectedUser">
        <div class="detail-section">
          <h3>基本信息</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <label>用户标识：</label>
              <span class="user-token">{{ selectedUser.userToken }}</span>
            </div>
            <div class="detail-item">
              <label>设备指纹：</label>
              <span>{{ selectedUser.deviceFingerprint }}</span>
            </div>
            <div class="detail-item">
              <label>IP地址：</label>
              <span>{{ selectedUser.ipAddress }}</span>
            </div>
            <div class="detail-item">
              <label>浏览器信息：</label>
              <span class="user-agent">{{ selectedUser.userAgent }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h3>访问统计</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <label>访问次数：</label>
              <span>{{ selectedUser.visitCount || 0 }} 次</span>
            </div>
            <div class="detail-item">
              <label>预约次数：</label>
              <span>{{ selectedUser.bookingCount || 0 }} 次</span>
            </div>
            <div class="detail-item">
              <label>首次访问时间：</label>
              <span>{{ formatDateTime(selectedUser.firstVisitTime) }}</span>
            </div>
            <div class="detail-item">
              <label>最后访问时间：</label>
              <span>{{ formatDateTime(selectedUser.lastVisitTime) }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h3>时间记录</h3>
          <div class="detail-grid">
            <div class="detail-item">
              <label>创建时间：</label>
              <span>{{ formatDateTime(selectedUser.createdAt) }}</span>
            </div>
            <div class="detail-item">
              <label>更新时间：</label>
              <span>{{ formatDateTime(selectedUser.updatedAt) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="userDetailDialogVisible = false">
            <span class="btn-content">
              关闭
            </span>
          </button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  getAnonymousUsersService,
  exportAnonymousUsersService,
  getUserStatisticsService
} from '@/api/admin.js'

const router = useRouter()

// 用户数据
const users = ref([])
const total = ref(0)
const selectedUser = ref(null)
const userDetailDialogVisible = ref(false)

// 统计数据
const stats = ref({
  totalUsers: 0
})

// 搜索表单
const searchForm = ref({
  searchText: '',
  dateRange: [],
  sortType: 'desc'
})

// 状态
const tableLoading = ref(false)
const exportLoading = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 日期快捷选项
const dateShortcuts = [
  {
    text: '今天',
    value: () => {
      const today = new Date()
      return [today, today]
    }
  },
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 计算属性 - 格式化表格数据中的时间
const formatTableData = (data) => {
  if (!data) return []
  return data.map(item => ({
    ...item,
    createdAt: formatDateTime(item.createdAt),
    firstVisitTime: formatDateTime(item.firstVisitTime),
    lastVisitTime: formatDateTime(item.lastVisitTime)
  }))
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const result = await getUserStatisticsService()
    if (result.code === 200) {
      stats.value.totalUsers = result.data.totalUsers || 0
    } else {
      console.error('获取用户统计数据失败:', result.msg)
    }
  } catch (error) {
    console.error('获取统计数据异常:', error)
    stats.value = {
      totalUsers: 0
    }
  }
}

// 获取用户数据列表
const fetchUsers = async () => {
  try {
    tableLoading.value = true
    
    // 处理日期范围转换为开始和结束日期字符串
    let startDate = ''
    let endDate = ''
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      startDate = searchForm.value.dateRange[0] ? 
        searchForm.value.dateRange[0].toISOString().split('T')[0] : ''
      endDate = searchForm.value.dateRange[1] ? 
        searchForm.value.dateRange[1].toISOString().split('T')[0] : ''
    }
    
    // 构建查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      searchText: searchForm.value.searchText || '',
      startDate,
      endDate,
      sortType: searchForm.value.sortType || 'desc'
    }
    
    console.log('查询参数:', params)
    
    const result = await getAnonymousUsersService(params)
    if (result.code === 200) {
      users.value = formatTableData(result.data.items || [])
      total.value = result.data.total || 0
    } else {
      console.error('获取用户数据失败:', result.msg)
      ElMessage.error(result.msg || '获取用户数据失败')
      users.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取用户数据异常:', error)
    ElMessage.error('获取用户数据失败')
    users.value = []
    total.value = 0
  } finally {
    tableLoading.value = false
  }
}

// 搜索用户数据
const searchUsers = async () => {
  console.log('搜索条件:', searchForm.value)
  currentPage.value = 1 // 重置到第一页
  await fetchUsers()
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.value = {
    searchText: '',
    dateRange: [],
    sortType: 'desc'
  }
  currentPage.value = 1
  fetchUsers()
}

// 筛选条件变化处理
const handleFilterChange = async () => {
  currentPage.value = 1
  await fetchUsers()
}

// 导出用户数据
const exportUsers = async () => {
  try {
    exportLoading.value = true
    ElMessage.info('正在准备导出文件，请稍候...')
    
    // 处理日期范围转换为开始和结束日期字符串
    let startDate = ''
    let endDate = ''
    if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
      startDate = searchForm.value.dateRange[0] ? 
        searchForm.value.dateRange[0].toISOString().split('T')[0] : ''
      endDate = searchForm.value.dateRange[1] ? 
        searchForm.value.dateRange[1].toISOString().split('T')[0] : ''
    }
    
    // 构建导出参数
    const exportParams = {
      searchText: searchForm.value.searchText || '',
      startDate,
      endDate,
      sortType: searchForm.value.sortType || 'desc'
    }
    
    console.log('导出参数:', exportParams)
    
    const result = await exportAnonymousUsersService(exportParams)
    
    // 创建下载链接
    const blob = new Blob([result], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    
    const filename = `匿名用户列表_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.download = filename
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('用户数据导出成功')
    
  } catch (error) {
    console.error('导出数据异常:', error)
    ElMessage.error(error.message || '导出数据失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}

// 查看用户详情
const viewUserDetail = (user) => {
  selectedUser.value = user
  userDetailDialogVisible.value = true
}

// 分页处理
const handleSizeChange = async (val) => {
  pageSize.value = val
  currentPage.value = 1
  await fetchUsers()
}

const handleCurrentChange = async (val) => {
  currentPage.value = val
  await fetchUsers()
}

// 工具函数
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '未知'
  
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

const truncate = (str, maxLength) => {
  if (!str) return ''
  if (str.length <= maxLength) return str
  return str.substring(0, maxLength) + '...'
}

// 返回仪表板
const goBack = () => {
  router.push('/dashboard')
}

onMounted(async () => {
  ElMessage.success('匿名用户管理页面加载成功')
  
  // 获取用户列表和统计数据
  await fetchUsers()
  await fetchStats()
})
</script>

<style scoped>
.users-management {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0;
}

/* 复用 Dashboard.vue 的样式 */
.dashboard-header,
.header-content,
.header-left,
.header-right,
.page-title,
.page-subtitle,
.stats-section,
.stats-grid,
.stat-card,
.stat-icon,
.stat-content,
.stat-number,
.stat-label,
.users-section,
.section-header,
.section-title,
.section-actions,
.export-btn,
.search-panel,
.search-form,
.form-row,
.form-item,
.form-actions,
.search-btn,
.reset-btn,
.table-panel,
.table-header,
.table-info,
.table-container,
.pagination-container,
.user-detail-dialog,
.detail-section,
.detail-grid,
.detail-item,
.dialog-footer {
  /* 继承 Dashboard.vue 的所有样式 */
}

/* 用户管理特有的样式 */
.user-token {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  color: #667eea;
  font-size: 12px;
}

.device-fingerprint {
  font-family: 'Courier New', monospace;
  color: #666;
  font-size: 12px;
}

.ip-address {
  font-family: 'Courier New', monospace;
  color: #666;
}

.user-agent {
  color: #888;
  font-size: 12px;
  line-height: 1.4;
  word-break: break-all;
}

.visit-time {
  font-size: 12px;
  color: #666;
}

.created-time {
  font-size: 12px;
  color: #888;
}

.back-btn {
  padding: 12px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  color: #666;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.back-btn:hover {
  background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 通用按钮样式 */
.export-btn, .search-btn, .reset-btn {
  padding: 12px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.export-btn:hover, .search-btn:hover, .reset-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
}

.export-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.btn-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-icon {
  font-size: 1rem;
}

.btn-loading {
  display: flex;
  align-items: center;
  gap: 10px;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.cancel-btn {
  padding: 12px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  color: #666;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.cancel-btn:hover {
  background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-header {
    padding: 20px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .stats-section,
  .users-section {
    padding-left: 20px;
    padding-right: 20px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .form-row {
    flex-direction: column;
    gap: 10px;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: flex-end;
  }
}
</style> 